import { Http } from "./request.js";
import { APP_BASE_API } from "@/config";
import { getToken } from "@/utils/storage";

export class XHR extends Http {
  // eslint-disable-next-line no-useless-constructor
  constructor() {
    super();
  }

  get(url, data = {}, header) {
    return new Promise((resolve, reject) => {
      this.request({
        url: url,
        method: "GET",
        data: data,
        header: header
      }).then(res => {
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  }

  post(url, data = {}, header) {
    return new Promise((resolve, reject) => {
      this.request({
        url: url,
        method: "POST",
        data: data,
        header: header
      }).then(res => {
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  }

  put(url, data = {}, header) {
    return new Promise((resolve, reject) => {
      this.request({
        url: url,
        method: "PUT",
        data: data,
        header: header
      }).then(res => {
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  }

  delete(url, data = {}, header) {
    return new Promise((resolve, reject) => {
      this.request({
        url: url,
        method: "DELETE",
        data: data,
        header: header
      }).then(res => {
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  }

  options(url, data = {}, header) {
    return new Promise((resolve, reject) => {
      this.request({
        url: url,
        method: "OPTIONS",
        data: data,
        header: header
      }).then(res => {
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  }

  /**
   * 上传文件
   * @param url
   * @param filePath
   * @param data
   * @param name
   * @returns {Promise<unknown>}
   */
  upload(url, filePath, data, name = "file") {
    const baseUrl = APP_BASE_API; // 后台请求接口的公共部分
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: baseUrl + url,
        filePath: filePath,
        name: name,
        header: {
          Authorization: getToken() ? "Bearer " + getToken() : ""
        },
        formData: data,
        // #ifdef MP-ALIPAY
        fileType: "image",
        // #endif
        success: (res) => {
          const { errMsg } = res;
          if (errMsg === "uploadFile:ok") {
            res = JSON.parse(res.data);
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }
}

